package com.zzyl.nursing.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService weChatService;
    private List<String> nickNameList = Arrays.asList("好柿开花", "大吉大利", "今晚吃鸡", "三羊开泰");


    @Autowired
    private TokenService tokenService;


    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public LoginVo login(UserLoginDto dto) {
        //1. 获取微信唯一身份标识openId
        String openId = weChatService.getOpenId(dto.getCode());
        if (StringUtils.isBlank(openId)) {
            throw new BaseException("登录失败");
        }
        //2. 根据openId查询用户
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        //3. 如果用户不存在则新增用户（自动注册）
        if (member == null) {
            Collections.shuffle(nickNameList);//打乱
            //生成随机名称
            String nickName = nickNameList.get(0) + RandomStringUtils.randomNumeric(4);
            member = FamilyMember.builder()
                    .openId(openId)
                    .name(nickName)
                    .build();
            this.save(member);
        }
        //4. 如果手机号不存在则获取微信绑定的手机号
        if (StringUtils.isBlank(member.getPhone())) {
            String phoneNum = weChatService.getPhone(dto.getPhoneCode());
            //5. 更新手机号到用户表
            if (StringUtils.isNotBlank(phoneNum)) {
                this.lambdaUpdate()
                        .eq(FamilyMember::getId, member.getId()) //更新条件
                        .set(FamilyMember::getPhone, phoneNum)//更新字段对应的值
                        .update();
            }
        }
        //6. 基于userId和昵称生成Token令牌
        String token = tokenService.createToken(Map.of(
                "userId", member.getId(),
                "nickName", member.getName()));
        //7. 封装响应结果对象
        return LoginVo.builder().nickName(member.getName()).token(token).build();
    }

}
